package com.shenjun.union.servers;

import com.shenjun.union.config.UnionBankConfig;
import com.shenjun.union.handler.HelloClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

@Component
public class HelloClient {

    @Autowired
    private HelloClientHandler helloClientHandler;

    private ChannelFuture channelFuture;

    @Autowired
    private UnionBankConfig unionBankConfig;

    @PostConstruct
    public void start() throws Exception {
        channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(helloClientHandler)
                .connect(new InetSocketAddress(unionBankConfig.getIp(), Integer.parseInt(unionBankConfig.getPort())))
                .sync();
    }

    public ChannelFuture writeAndFlush(Object msg) {
        return channelFuture.channel().writeAndFlush(msg);
    }
}
